package vip.aster.framework.repeat;

import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import vip.aster.common.annotation.RepeatSubmit;
import vip.aster.common.utils.HttpContextUtils;
import vip.aster.common.utils.ResultInfo;

import java.lang.reflect.Method;

/**
 * 防止重复提交拦截器
 *
 * @author Aster
 * @since 2024/2/1 10:13
 */
@Slf4j
@Component
public abstract class RepeatSubmitInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            log.warn("Handler is not an instance of HandlerMethod. Allowed to proceed.");
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
        if (annotation == null) {
            return true;
        }
        if (this.isRepeatSubmit(request, annotation)) {
            HttpContextUtils.renderString(response, JSONObject.toJSONString(ResultInfo.failed(annotation.message())));
            return false;
        }
        return true;
    }

    /**
     * 验证是否重复提交由子类实现具体的防重复提交的规则
     */
    public abstract boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation);

}
